package com.zhong.system.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhong.common.annotation.DataScope;
import com.zhong.common.constant.UserConstants;
import com.zhong.common.core.domain.TreeSelect;
import com.zhong.common.core.domain.entity.SysDept;
import com.zhong.common.exception.ServiceException;
import com.zhong.common.utils.StringUtils;
import com.zhong.common.utils.WrapperUtils;
import com.zhong.common.utils.spring.SpringUtils;
import com.zhong.system.mapper.SysDeptMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author zhongzc
 */
@Service
@RequiredArgsConstructor
public class SysDeptService extends ServiceImpl<SysDeptMapper, SysDept>
{
    private final SysUserDeptService userDeptService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return list(WrapperUtils.<SysDept>getLambdaQueryWrapper(dept).orderByAsc(SysDept::getOrderNum));
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<String> tempList = depts.stream().map(SysDept::getId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    public boolean checkDeptNameUnique(SysDept dept)
    {
        SysDept oldDept = getOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDeptName,dept.getDeptName())
                .eq(SysDept::getParentId,dept.getParentId()).eq(SysDept::getDelFlag,UserConstants.NORMAL));
        if (StringUtils.isNotNull(oldDept) && !oldDept.getId().equals(dept.getId()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    public boolean insertDept(SysDept dept)
    {
        SysDept parent = getById(dept.getParentId());
        if(parent!=null){
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.NORMAL.equals(parent.getStatus()))
            {
                throw new ServiceException("部门停用，不允许新增");
            }
            dept.setAncestors(parent.getAncestors() + "," + dept.getParentId());
        }else {
            dept.setAncestors("0");
        }
        return save(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Transactional
    public boolean updateDept(SysDept dept)
    {
        SysDept oldDept = getById(dept.getId());
        if(!oldDept.getParentId().equals(dept.getParentId())){
            if ("0".equals(dept.getParentId())) {
                dept.setAncestors("0");
            }else {
                SysDept parentDept = getById(dept.getParentId());
                String newAncestors = parentDept.getAncestors() + "," + parentDept.getId();
                dept.setAncestors(newAncestors);

                if(UserConstants.DISABLE.equals(parentDept.getStatus())){
                    dept.setStatus(UserConstants.DISABLE);
                }
            }
            List<SysDept> children = list(Wrappers.<SysDept>lambdaQuery().likeRight(SysDept::getAncestors,oldDept.getAncestors()+","+oldDept.getId()));
            for(SysDept child : children){
                child.setAncestors(child.getAncestors().replaceFirst(oldDept.getAncestors(), dept.getAncestors()));
                updateById(child);
            }
        }

        if(!oldDept.getStatus().equals(dept.getStatus())){
            if(UserConstants.NORMAL.equals(dept.getStatus())){
                //将上级部门设置为启用
                update(Wrappers.<SysDept>lambdaUpdate().in(SysDept::getId, Arrays.asList(dept.getAncestors().split(","))).set(SysDept::getStatus,UserConstants.NORMAL));
            }else if(UserConstants.DISABLE.equals(dept.getStatus())){
                update(Wrappers.<SysDept>lambdaUpdate().likeRight(SysDept::getAncestors,dept.getAncestors()+","+dept.getId()).set(SysDept::getStatus,UserConstants.DISABLE));
            }
        }
        return updateById(dept);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 根据ID删除部门，已经下属部门
     * @param id
     */
    @Transactional
    public void removeDept(String id){
        SysDept dept = getById(id);
        //一、删除下级部门
        remove(Wrappers.<SysDept>lambdaQuery().likeRight(SysDept::getAncestors,dept.getAncestors()+","+dept.getId()));

        //二、删除部门分配信息
        userDeptService.removeByDeptId(id);

        removeById(id);
    }
}
